import md5 from "js-md5"
import * as cache from './storage.js'
import{VERSION,storageKey,unauthPath,sign} from './constant.js'
import {base_list, getBaseUrl, initTask, setBaseUrl} from "@/utils/config.js"
import {toast,getNetworkType} from '@/utils/util.js'
let loopCount = 3 
import store  from '@/store/index.js'

export const request=(options)=>{
	return new Promise((resolve,reject)=>{
		uni.request({
			method:'POST',
			dataType:'json',
			...options,
			success(rs){
				resolve(rs)
			},
			fail(e){
				reject(e)
			}
		})
	})
}

export const defaultBefore = async (options)=>{
	const token = await cache.get(storageKey.token);
//	console.log(token)
	options.data = sortAsc(options.data);
	const systemInfo = getApp().globalData.systemInfo
	options.header={
		token:token||'',
		...options.header,
		sign:encryption(options.data),
		'user-brand':systemInfo.brand,
		'user-model':systemInfo.model,
		'user-platform':systemInfo.platform,
		'user-system':systemInfo.system,
		// #ifdef APP-PLUS
		"user-channel":'APP',
		// #endif
		// #ifdef MP-WEIXIN
		"user-channel":'wxMini',
		// #endif
		// #ifdef H5
		"user-channel":'H5',
		// #endif
		'user-version':VERSION
	}
	if(options.method=='GET'){
		const fromList = data2formList(options.data);
		fromList.push(`token=${token||''}`)
		const sign = encryption(fromList.join('&'));
		fromList.push(`sign=${sign}`)
		options.url+=`?${fromList.join('&')}`
	}
	let getUserInfo = options.getUserInfo
//	console.log(getUserInfo,'getUserInfo')
	if (getUserInfo) {
	  let sessionUserInfo = await cache.get(storageKey.sessionUserInfo);
	  console.log(sessionUserInfo,'sessionUserInfo')
	  if (!sessionUserInfo.userName) {
	    uni.navigateTo({
	      url: unauthPath 
	    });
	    throw new Error('未登录')
	  }
	}
	delete options.getUserInfo
	return options
}
export const defaultAfter = async (res,options)=>{
	let {data} = res;
	if (options.requestType == 'tencent') {
		data = JSON.parse(data);
		return data;
	}else{
		if (data.retCode === '000000') {
			return data.data; 
		}	
		if (data.retCode === '12580') {
			store.dispatch('user/logout');
			uni.navigateTo({
				url: unauthPath 
			})
			throw data
		}
		console.error(res,options) 
		if (data.retDesc) {
			toast(data.retDesc);
			throw data
		} else {
			toast(JSON.stringify(data));
			throw data
		}
	}
	return res
}
export const silentAfter = async (res,options)=>{
	let {data} = res;
	if (options.requestType == 'tencent') {
		data = JSON.parse(data);
		return data;
	}else{
		if (data.retCode === '000000') {
			return data.data; 
		}	
		if (data.retCode === '12580') {
			store.dispatch('user/logout');
			uni.navigateTo({
				url: unauthPath 
			})
			throw data
		}
		throw data
	}
	return res
}



export const ajax = async(options,before=defaultBefore,after=defaultAfter)=>{
	await initTask
	try{
		await before(options)
		let res = null
		// for (let i = 1; i <= base_list.length*loopCount; i++) {
		for (let i = 0; i <= base_list.length*loopCount; i++) {
			try{
				const curOptions = {...options}
				curOptions.url = /^http/.test(curOptions.url)?curOptions.url:`${getBaseUrl()}${curOptions.url}`;
				res = await request(curOptions);
				break;
			}catch(e){
                console.log(base_list,i,'base_list')
				let valueToRemove = "https://feidao.weixin.com";
				let indexToRemove = base_list.indexOf(valueToRemove);
				console.log(indexToRemove)
				if (indexToRemove !== -1) {
				    base_list.splice(indexToRemove, 1);
				}
				console.log('----------')
				console.log(base_list)
				setBaseUrl(base_list[i%base_list.length])
				if(i>=base_list.length*loopCount){
					throw e
				}
			}
		}
		res = await after(res,options);
		return res;
	}catch(e){
		getNetworkType().then(({networkType})=>{
			if(networkType=='none'){
				toast('网络连接断开，请检查网络设置')
			}
		});
		throw e
	}
}

export const encryption = (param)=>{
	const type = typeof param
	if(param === null){
		return md5(sign)
	}else if(type == 'string'){
		return md5(param+sign)
	}else if(type == 'object'){
		const str = JSON.stringify(param)
		return md5(str+sign)
	}else{
		return md5(sign)
	}
}

export const data2formList = (data = {}) =>{
	return Object.entries(data).map(([key,value])=>`${key}=${value}`)
}


export const sortAsc = (jsonObj) => {
	if(!jsonObj){return}
	const arr = Object.keys(jsonObj).sort();
	return arr.reduce((p,n)=>{
		p[n] = jsonObj[n]
		return p
	},{})
}